package com.wei.util;

import io.jsonwebtoken.*;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

@Data // 需要加`@Data`注解才能读到配置内容
@Component
@ConfigurationProperties(prefix = "jwt.token")
public class JwtHelper {

    private Integer expiration;

    private String signKey;

    private final String userIdKey = "userId";

    /**
     * 生成token字符串
     */
    public String createToken(Integer userId) {
        return Jwts.builder()
                .setSubject("user-info")
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000 * 60)) // 乘以 1000 * 60, 则单位分钟
                .claim(this.userIdKey, userId)
                .signWith(SignatureAlgorithm.HS512, signKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
    }

    /**
     * 从token字符串获取userid
     */
    public Integer getUserId(String token) throws RuntimeException {
        Claims claims;
        try {
            Jws<Claims> claimsJws = Jwts.parser()
                    .setSigningKey(this.signKey)
                    .parseClaimsJws(token);
            claims = claimsJws.getBody();
        } catch (ExpiredJwtException e) {
            throw new RuntimeException("token过期");
        } catch (Exception e) {
            throw new RuntimeException("token错误");
        }
        return (Integer) claims.get(this.userIdKey);
    }

    /**
     * 判断token是否有效
     */
    public boolean isExpiration(String token){
        try {
            //没有过期，有效，返回false
            return Jwts.parser()
                    .setSigningKey(this.signKey)
                    .parseClaimsJws(token)
                    .getBody()
                    .getExpiration()
                    .before(new Date());
        }catch(Exception e) {
            //过期出现异常，返回true
            return true;
        }
    }

}
